package com.gim.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Component
@ChannelHandler.Sharable // 保证单例，避免重复创建
public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(MyChannelHandler.class);
    @Value("${secret.key}")
    private static String SECRET_KEY; // 16字节密钥用于AES
    @Value("${secret.iv}")
    private static String FIXED_IV; // 16字节固定IV用于AES

    @Autowired
    private ChannelManager channelManager;

    // 当连接建立
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("客户端连接已建立: " + ctx.channel().remoteAddress());
        // 通常在这里认证用户（例如从 ctx.channel().attr() 获取 userId）
        // 假设你已通过登录协议绑定了 userId 到 channel
        String userId = getUserIdFromChannel(ctx.channel()); // 自定义逻辑
        if (userId != null) {
            channelManager.addChannel(userId, ctx.channel());
        }
    }

    // 当连接断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("客户端连接已断开: " + ctx.channel().remoteAddress());
        logger.info("用户已下线: {}", getUserIdFromChannel(ctx.channel()));
        channelManager.removeChannel(ctx.channel());
        ctx.close();
    }

    // 处理业务消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("接收到客户端数据");
        logger.info("用户已上线: {}", getUserIdFromChannel(ctx.channel()));
        ByteBuf msgs = (ByteBuf) msg;
        byte[] data = new byte[msgs.readableBytes()];
        msgs.readBytes(data);
        
        try {
            // 解密数据
            byte[] decryptedData = decryptData(data, SECRET_KEY);
            
            // 直接转换为字符串并打印
            String receivedString = new String(decryptedData, StandardCharsets.UTF_8);
            System.out.println("接收到的解密数据: " + receivedString);
            logger.info("接收到的解密数据: {}", receivedString);
        } catch (Exception e) {
            logger.error("数据解密失败: {}", e.getMessage());
            e.printStackTrace();
        }
    }

    // 异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("异常发生: {}", cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

    // 示例：从 Channel 属性中获取 userId（需在登录时设置）
    private String getUserIdFromChannel(Channel channel) {
        try {
            Object attr = channel.attr(AttributeKey.valueOf("userId")).get();
            return attr != null ? attr.toString() : null;
        } catch (Exception e) {
            return null;
        }
    }
    
    // AES解密方法 - 使用固定IV
    private byte[] decryptData(byte[] data, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // 使用固定IV (16字节)
        IvParameterSpec ivSpec = new IvParameterSpec(FIXED_IV.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return cipher.doFinal(data);
    }
}